文章目录
  1. 1. Objective-C RegEx

Objective-C RegEx

Objective-C RegEx Categories
https://github.com/bendytree/Objective-C-RegEx-Categories
使用说明:将 RegExCategories.h RegExCategories.m
文件拖入工程中引入头文件即可.
 \

==========================================================================
    //匹配电话号码(手机号以13, 15,18开头,八个 \d
数字字符)
    BOOL isMatch = [ “15910514636” isMatch:RX( “
^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$“)];
    NSLog( “%d”, isMatch);
 
    //
匹配邮箱
    BOOL isMatch = [ “<705786230 qq.com>” isMatch:RX( “
[A-Z0-9a-z._%+-]+ [A-Za-z0-9.-]+\\.[A-Za-z]{2,4}“)];
    NSLog( “%d”, isMatch);
   
    //
匹配用户名(用户名长度为6-20位之间,大小写字母或者数字均可)
    BOOL isMatch = [ “705786230” isMatch:RX( “
^[A-Za-z0-9]{6,20}+$“)];
    NSLog( “%d”, isMatch);
 \

    //匹配身份证号
    BOOL isMatch = [ “42120919831025587X” isMatch:RX( “
^(\\d{14}|\\d{17})(\\d|[xX])$“)];
    NSLog( “%d”, isMatch);\

==========================================================================
 
    //创建一个正则表达式
    Rx* rx = RX( “\\d”);
    Rx* rx = [Rx rx: “\\d”];
    Rx* rx = [Rx rx: “\\d” ignoreCase:YES];
    
    //
判断字符串是否匹配
    BOOL isMatch = [ “2345” isMatch:RX( “^\\d+$“)];
    
    //
获取匹配的字符串
    NSString* age = [ “My dog is 3.” firstMatch:RX( “\\d+”)];
    
    //
获取匹配的结果存储进数组
    NSArray* words = [ “Hey pal” match:RX( “\\w+”)];
    // words => [ “Hey”, “pal” ]
    
    //
能获取详细信息的匹配
    RxMatch* match = [ “12.34, 56.78”
firstMatchWithDetails:RX( “\\d+([.]\\d+)”)];
    // match.value => “12.34”
    // match.range => NSRangeMake(0, 5);
    // match.original => “12.34, 56.78”;
    // match.groups => [ RxMatchGroup, RxMatchGroup ];
    
    //
使用模板来替换匹配的字符串
    NSString* result = [ “My dog is 12.” replace:RX( “\\d+”)
with: “old”];
    // result => “My dog is old.”
    
    //
使用block来替换
    NSString* result = [RX( “\\w+”) replace: “hi bud”
withBlock:^(NSString* match){
        return [NSString stringWithFormat: “%i”, match.length];
    }];
    // result => “2 3”
    
    //
获取详细匹配信息的block方式
    NSString* result = [RX( “\\w+”) replace: “hi bud”
withDetailsBlock:^(RxMatch* match){
        return [NSString stringWithFormat: “%i”,
match.value.length];
    }];
    // result => “2 3”\

==========================================================================\

总结:正则表达式可用来按照一定模式来实现匹配字符串,替换字符串等等强大的功能,详细使用说明请参考该开源框架的使用示例.
 
 
 
其他:使用谓词来处理正则表达式示例
==========================================================================
    NSString
*email = “<YouXianMing 163.com>”;

    NSString
*regex =
“[A-Z0-9a-z._%+-]+ [A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”;

   
NSPredicate *predicate = [NSPredicate predicateWithFormat: “SELF
MATCHES % “, regex];

    BOOL
isValid = [predicate evaluateWithObject:email];

==========================================================================


文章目录
  1. 1. Objective-C RegEx